import random
import heapq
class Process:
    def __init__(self, pid, time):
        self.pid = pid
        self.run_time = time
        self.waiting = 0
        self.start_time = 0
        self.end_time = 0

    def __lt__(self, other):
        return self.run_time < other.run_time
class SJF:
    def __init__(self):
        self.heap = []
        heapq.heapify(self.heap)
        self.current_time = 0
        self.completed = []


    def add_process(self, process):
        heapq.heappush(self.heap,process)

    def run(self):
        print("调度开始")
        while self.heap:

            process = heapq.heappop(self.heap)
            process.start_time = self.current_time
            process.waiting = process.start_time
            process.end_time = self.current_time + process.run_time
            self.current_time += process.run_time
            self.completed.append(process)
    def print_process(self):
        print("PID\t开始执行时间\t执行时间\t等待时间\t周转时间")
        turntime = 0
        for p in self.completed:
            print(f"{p.pid}\t\t{p.start_time}\t\t{p.run_time}\t\t{p.waiting}\t\t{p.end_time}")
            turntime += p.end_time
        print(f"平均周转时间{turntime / len(self.completed)}")
if __name__ == "__main__":
    sjf = SJF()
    process = []
    for pid in range(1, random.randint(1, 100)):
        time = random.randint(10, 100)
        process.append(Process(pid, time))
    for p in process:
        sjf.add_process(process=p)
    sjf.run()
    sjf.print_process()